import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/calendar_header.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/menstrual_mode.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:table_calendar/table_calendar.dart';

typedef LoadEventCallback = List<MenstrualEvent> Function(DateTime day);
typedef SelectedDayCallback = void Function(DateTime selectedDay, DateTime focusedDay, ValueNotifier<DateTime> focusedDayNotify);

class CycleTableCalendar extends StatefulWidget {
  const CycleTableCalendar({super.key, required this.onEventLoad, required this.onSelectedDay});

  final LoadEventCallback onEventLoad;
  final SelectedDayCallback onSelectedDay;

  @override
  State<CycleTableCalendar> createState() => _CycleTableCalendarState();
}

class _CycleTableCalendarState extends State<CycleTableCalendar> {
  late PageController _pageController;

  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;
  final DateTime _firstDay = DateUtils.addMonthsToMonthDate(DateTime.now(), -3);
  final DateTime _lastDay = DateTime.now();

  final ValueNotifier<DateTime> _focusedDay = ValueNotifier(DateTime.now());
  late final ValueNotifier<List<MenstrualEvent>> _selectedEvents;

  late CalendarFormat _calendarFormat = CalendarFormat.month;
  final RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOn;

  _onDaySelected(DateTime selectedDay, DateTime focusedDay, ValueNotifier<DateTime> focusedDayNotify) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        focusedDayNotify.value = focusedDay;
        // _rangeStart = null; // Important to clean those
        // _rangeEnd = null;
        // _rangeSelectionMode = RangeSelectionMode.toggledOff;
        _selectedEvents.value = widget.onEventLoad(selectedDay);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _selectedDay = _focusedDay.value;
    _selectedEvents = ValueNotifier(widget.onEventLoad(_selectedDay!));
  }

  @override
  void dispose() {
    _focusedDay.dispose();
    _selectedEvents.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ValueListenableBuilder<DateTime>(
            valueListenable: _focusedDay,
            builder: (context, value, _) {
              return CalendarHeader(
                locale: Get.locale?.languageCode,
                focusedDay: value,
                onLeftArrowTap: () => {
                  _pageController.previousPage(
                    duration: const Duration(milliseconds: 300),
                    curve: Curves.easeOut,
                  )
                },
                onRightArrowTap: () => {
                  _pageController.nextPage(
                    duration: const Duration(milliseconds: 300),
                    curve: Curves.easeOut,
                  )
                },
                onTodayButtonTap: () => {},
                onClearButtonTap: () => {},
              );
            }),
        Container(
          padding: EdgeInsets.symmetric(vertical: 50.h, horizontal: 50.w),
          decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
          child: Column(
            children: [
              TableCalendar<MenstrualEvent>(
                rowHeight: 40,
                locale: Get.locale?.languageCode,
                firstDay: _firstDay,
                lastDay: _lastDay,
                focusedDay: _focusedDay.value,
                calendarFormat: _calendarFormat,
                headerVisible: false,
                startingDayOfWeek: Get.locale?.languageCode == 'zh' ? StartingDayOfWeek.monday : StartingDayOfWeek.sunday,
                selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                rangeSelectionMode: _rangeSelectionMode,
                // rangeStartDay: state.rangeStart,
                // rangeEndDay: state.rangeEnd,
                eventLoader: (day) => widget.onEventLoad(day),
                onPageChanged: (focusedDay) {
                  _focusedDay.value = focusedDay;
                },
                onDaySelected: (selectedDay, focusedDay) => widget.onSelectedDay(selectedDay, focusedDay, _focusedDay),
                // onRangeSelected: (start, end, focusedDay) => _.onRangeSelected(start, end, focusedDay),
                onCalendarCreated: (controller) => _pageController = controller,
                onFormatChanged: (format) {
                  if (_calendarFormat != format) {
                    setState(() {
                      _calendarFormat = format;
                    });
                  }
                },
                calendarBuilders: CalendarBuilders<MenstrualEvent>(
                  // withinRangeBuilder: (context, day, focusedDay) {
                  //   return Container(
                  //     margin: const EdgeInsets.only(top: 40),
                  //     padding: const EdgeInsets.all(1),
                  //     width: 7,
                  //     decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.primaries[Random().nextInt(Colors.primaries.length)]),
                  //   );
                  // },
                  markerBuilder: (context, day, events) {
                    if (events.isEmpty) return const SizedBox();
                    return Container(
                      margin: const EdgeInsets.only(top: 40),
                      padding: const EdgeInsets.all(1),
                      width: 7,
                      // decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.primaries[Random().nextInt(Colors.primaries.length)]),
                    );
                  },
                ),
                calendarStyle: CalendarStyle(
                  outsideDaysVisible: false,
                  markersAlignment: Alignment.topRight,
                  todayTextStyle: const TextStyle(color: Colors.black54),
                  todayDecoration: BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                    border: Border.all(width: 1, color: Colors.red),
                  ),
                  selectedDecoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
                ),
              ),
              SizedBox(height: 70.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Container(
                        height: 30.h,
                        width: 30.w,
                        decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(100.r)),
                      ),
                      SizedBox(width: 20.w),
                      Text(LocaleKeys.cycle_calendar_during_text.ts),
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        height: 30.h,
                        width: 30.w,
                        decoration: BoxDecoration(color: Colors.amberAccent, borderRadius: BorderRadius.circular(100.r)),
                      ),
                      SizedBox(width: 20.w),
                      Text(LocaleKeys.cycle_calendar_measurement_text.ts),
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        height: 30.h,
                        width: 30.w,
                        decoration: BoxDecoration(color: Colors.green, borderRadius: BorderRadius.circular(100.r)),
                      ),
                      SizedBox(width: 20.w),
                      Text(LocaleKeys.cycle_calendar_ovulation_text.ts),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }
}
